package com.ff.neuropp.jwt;


import com.ff.neuropp.domain.Auth;
import com.ff.neuropp.domain.SystemLog;
import com.ff.neuropp.domain.User;
import com.ff.neuropp.service.AuthService;
import com.ff.neuropp.service.SystemLogService;
import com.ff.neuropp.service.UserService;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

@Component
public class CorsFilter implements Filter {

    @Resource
    private SystemLogService systemLogService;

    @Resource
    private UserService userService;

    @Resource
    private AuthService authService;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String url = request.getServletPath();
        if (isWhiteListUrl(url)) {
            response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
            response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
            response.setHeader("Access-Control-Max-Age", "3600");
            response.setHeader("Access-Control-Allow-Headers", "token,Content-Type");
            response.setHeader("Access-Control-Allow-Credentials", "true"); //是否支持cookie跨域
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }
        //filterChain.doFilter(servletRequest, servletResponse);//remove after testing

        String token = request.getHeader("token");
        String account = "";
        if (token != null && token.length() > 0) {
            account = JwtHelper.parseToken(token);
        }
        //account = "admin"; for local testing

        if (null != account && account.length() > 0) {
            //记录日志
            SystemLog systemLog = new SystemLog();
            systemLog.setLogAccount(account);
            User user = userService.findUserByAccount(account);
            systemLog.setLogName(user.getName());
            systemLog.setLogJobNumber(user.getJobNumber());
            systemLog.setLogurl(url);
            Auth auth = authService.findByUrl(url);
            if(null != auth ) {
                systemLog.setLogContent(auth.getName());
            }
            systemLog.setLogIp(request.getRemoteHost());
            systemLogService.save(systemLog);

            response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
            response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
            response.setHeader("Access-Control-Max-Age", "3600");
            response.setHeader("Access-Control-Allow-Headers", "token,Content-Type");
            response.setHeader("Access-Control-Allow-Credentials", "true"); //是否支持cookie跨域
            filterChain.doFilter(servletRequest, servletResponse);
        } else {
            response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
            response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
            response.setHeader("Access-Control-Max-Age", "3600");
            response.setHeader("Access-Control-Allow-Headers", "token,Content-Type");
            response.setHeader("Access-Control-Allow-Credentials", "true"); //是否支持cookie跨域
            response.setHeader("Access-Control-Expose-Headers", "sessiontimeout");
            response.setHeader("sessiontimeout", "true");
        }


    }

    private boolean isWhiteListUrl(String url) {
        //return true;
        if (url.equals("/api/user/login") || url.equals("/api/user/logout") || url.equals("/api/user/getverify") || url.contains("/api/excel/import")
                || url.equals("/api/file/uploadfile")|| url.equals("/api/file/getimg")|| url.equals("/api/question/create")
                || url.equals("/api/schooldata/getschooltype") || url.equals("/api/school/list") || url.equals("/api/schooldata/listbytype")
                || url.equals("/api/questionnaire/findbyid") || url.equals("/api/questionnaire/submit") || url.equals("/api/school/list") || url.equals("/api/school/updateschoolData")
                || url.startsWith("/swagger") || url.startsWith("/webjars/springfox-swagger-ui") || url.equals("/v2/api-docs")
                || url.startsWith("/upload") || url.startsWith("/app") || url.startsWith("/api/file")) {
            return true;
        }else {
            return false;
        }

    }

    @Override
    public void destroy() {

    }

    private String key = "E1012349BA59ABBE56E057F123483E234";

    private String getSha1(String account, String stamp) throws OutOfMemoryError,
            IOException, NoSuchAlgorithmException {
        String data = key + account + stamp;
        MessageDigest md = MessageDigest.getInstance("SHA1");
        md.update(data.getBytes());
        StringBuffer buf = new StringBuffer();
        byte[] bits = md.digest();
        for (int i = 0; i < bits.length; i++) {
            int a = bits[i];
            if (a < 0) {
                a += 256;
            }
            if (a < 16) {
                buf.append("0");
            }
            buf.append(Integer.toHexString(a));
        }
        return buf.toString();
    }
}
